<?php
namespace app\job;

use think\facade\Queue;
use think\facade\Db;
use think\exception\ValidateException;
use think\queue\Job;

class UpdateCourseRule
{
    // 课程学习明细
    public function fire(Job $job, array $data)
    {

        $isJobDone = $this->doUpdateCourseRule($data);

        if ($isJobDone['code'] == 0) {

            $job->delete();

            // 1.当前任务由哪个类来负责处理
            // 当轮到该任务时，系统将生成该类的实例，并调用其fire方法
            $jobHandlerClassName = 'app\job\UpdateCourseRule';

            // 2.当任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName = "UpdateCourseRule";


            // 3.当前任务所需业务数据，不能为resource类型，其他类型最终将转化为json形式的字符串
            $jobData = ['ts' => $isJobDone['ts'], 'page' => $isJobDone['page'], 'timing_id' => $isJobDone['timing_id'], 'type' => $isJobDone['type']];

            // 4.将该任务推送到消息列表，等待对应的消费者去执行
            // 入队列，later延迟执行，单位秒，push立即执行
            Queue::push($jobHandlerClassName, $jobData, $jobQueueName);

        } elseif($isJobDone['code'] == 1) {

            $job->delete();

            Db::name('timing')->where('id', '=', $data['timing_id'])->update(['state' => 2, 'complete_time'=>time()]);
        } else {
            if ($job->attempts() > 3){
                $job->delete();
            }

        }

    }


    /**
     * 根据消息中的数据进行实际的业务处理...
     * @param array $data
     * @return bool
     */
    protected function doUpdateCourseRule(array $data)
    {

        //+更新课程规则

        if ($data['type'] == 1) {
            $courseid_data = Db::name('course')
                ->where('status', '=', 1)
                ->column('courseid');
        } else {
            $map1 = [
                ['a.status', '=', 1],
            ];

            $map2 = [
                ['a.start', '>=', time()],
            ];

            $courseid_data = Db::name('flex')
                ->alias('a')
                ->join('o_flex_course b', 'b.flex_id=a.id')
                ->whereOr([ $map1, $map2 ])
                ->column('b.courseid');
        }

        $rules = Db::name('course_rules')
            ->whereIn('courseid', $courseid_data)
            ->order('type', 'asc')
            ->page($data['page'], 1)
            ->select()
            ->toArray();

        if (!empty($rules)) {

            Db::startTrans();

            foreach ($rules as &$v) {
                $where = [];

                if (!empty($v['function'])) {
                    $where[] = ['function', 'in', $v['function']];
                }

                if (!empty($v['position'])) {
                    $where[] = ['position', 'in', $v['position']];
                }
                if (!empty($v['division'])) {
                    $where[] = ['division', 'in', $v['division']];
                }
                if (!empty($v['division_mt'])) {
                    $where[] = ['division_mt', 'in', $v['division_mt']];
                }
                if (!empty($v['entity'])) {
                    $where[] = ['entity', 'in', $v['entity']];
                }

                if (!empty($v['entity_mt'])) {
                    $where[] = ['entity_mt', 'in', $v['entity_mt']];
                }

                if (!empty($v['activity_sector'])) {
                    $where[] = ['activity_sector', 'in', $v['activity_sector']];
                }

                if (!empty($v['department_name'])) {
                    $where[] = ['department_name', 'in', $v['department_name']];
                }
                if (!empty($v['region'])) {
                    $where[] = ['region', 'in', $v['region']];
                }
                if (!empty($v['office_location'])) {
                    $where[] = ['office_location', 'in', $v['office_location']];
                }

                if (!empty($v['nationality'])) {
                    $where[] = ['nationality', 'in', $v['nationality']];
                }

                if (!empty($v['age'])) {
                    $where[] = ['age', trim($v['age_select']), $v['age']];
                }

                if (!empty($v['services_year'])) {
                    $where[] = ['services_year', trim($v['services_year_select']), $v['services_year']];
                }

                if (!empty($v['xiashu'])) {
                    $where[] = ['xiashu', trim($v['xiashu_select']), $v['xiashu']];
                }

                $where[] = ['status', '=', 1];

                if ($v['type'] == 2 ) {

                    $userid = Db::name('course_user')
                        ->where('courseid', '=', $v['courseid'])
                        ->where('recommend_type', '=', 1)
                        ->column('userid');

                    if (!empty($userid)) {
                        $where[] = ['userid', 'in',$userid];
                        $user = Db::name('Members')
                            ->where($where)
                            ->column('userid');
                    } else {
                        $user = Db::name('Members')
                            ->where($where)
                            ->column('userid');
                    }
                } else {
                    $user = Db::name('Members')->where($where)->column('userid');
                }



                if (empty($user)) {

                    $res = Db::name('course_user')
                        ->where('rules_id', '=', $v['id'])
                        ->where('type', '=', 1)
                        ->find();

                    if ($res) {

                        if (!Db::name('course_user')
                            ->where('rules_id', '=', $v['id'])
                            ->where('type', '=', 1)
                            ->delete()) {

                            Db::rollback();
                        }

                    }

                } else {

                    $old = Db::name('course_user')
                        ->where('rules_id', '=', $v['id'])
                        ->where('type', '=', 1)
                        ->column('userid');

                    $new = array_diff($user, $old);

                    $old_user = array_diff($old, $user);

                    $user_array = [];

                    if (!empty($new)) {
                        foreach ($new as &$val) {
                            $arr = array(
                                'courseid' => $v['courseid'],
                                'rules_id' => $v['id'],
                                'userid' => $val,
                                'type' => 1,
                                'recommend_type' => $v['type'],
                                'add_time' => time()
                            );
                            array_push($user_array, $arr);
                        }

                        $res = Db::name('course_user')->insertAll($user_array);

                        if (!$res) {
                            Db::rollback();
                        }
                    }

                    if (!empty($old_user)) {

                        if (!Db::name('course_user')
                            ->where('rules_id', '=', $v['id'])
                            ->where('type', '=', 1)
                            ->where('userid', 'in', $old_user)
                            ->delete()){
                            Db::rollback();
                        }

                    }
                }
            }
            Db::commit();
            return ['code' => 0, 'ts' => $data['ts'], 'page' => ($data['page'] + 1), 'timing_id' => $data['timing_id'], 'type' => $data['type']];

        } else {
            return ['code' => 1];
        }
    }


    protected function getSymbol($str)
    {
        if ($str == 'gt') {
            return '>';
        } else if ($str == 'egt') {
            return '>=';
        } else if ($str == 'lt') {
            return '<';
        } else if ($str == 'elt') {
            return '<=';
        } else if ($str == 'eq') {
            return '=';
        }
    }
}